import os

import aiofiles

from arequests.AsyncRequest import AsyncRequest


def get_dir():
    """ 不存在则创建目录"""
    # 项目跟路径
    root_path = './'
    img_dir = 'tea_images'
    directory = root_path + img_dir
    if not os.path.exists(directory):
        os.mkdir(directory)
    return directory


async def save_file(file_full_path, b):
    """下载文件"""
    # 如果文件存在，则跳过
    if os.path.exists(file_full_path):
        return
    # 异步方法写文件
    async with aiofiles.open(file_full_path, 'wb+') as fp:
        await fp.write(b)
        # print(file_full_path, '下载成功')


async def download(img_data):
    # 下载图片
    img_url = img_data['src']
    # print(img_url, '正在下载。。。')
    b = await AsyncRequest().getByte(img_url)
    file_name = img_url.split('/')[-1]
    file_full_path = get_dir() + "/" + file_name
    await save_file(file_full_path, b)
